﻿#Region "Imports"

Imports MS.WindowsAPICodePack.Internal.CoreHelpers
Imports Microsoft.WindowsAPICodePack
Imports Microsoft.WindowsAPICodePack.Taskbar
Imports Microsoft.WindowsAPICodePack.Dialogs

Imports SpeechLib

#End Region

Class MainWindow

#Region "Test"

    Private Sub SetLanguage()
        If My.Settings.Options_Language = "en-US" Then
            Dim l As New Languages.en_US
            FileMenuItem.ToolTip = l.DocumentMenuItem
        ElseIf My.Settings.Options_Language = "es-ES" Then
            'TODO: add es-ES language
            'Dim l As New Languages.es_ES
            'FileMenuItem.ToolTip = l.DocumentMenuItem
        End If
    End Sub

#End Region

#Region "Reuseable Code"

#Region "-Documents"

    Public Sub NewDocument(ByVal title As String)
        If TabCell.Items.Count > 0 Then
            SelectedDocument.IsSelected = False
        End If
        Dim tb As New DocumentTab(title)
        TabCell.Items.Add(tb)
        ResizeTabs(TabCell)
        tb.IsSelected = True
        SelectedDocument.SetFileType("Rich Text Document")
        SelectedDocument.TBox.Focus()
    End Sub

    Public Sub LoadDocument(ByVal file As DocumentTab, ByVal filename As String)
        file.DocumentName = filename
        Dim f As New IO.FileInfo(filename)
        SelectedDocument.SetDocumentTitle(f.Name)
        Dim fs As IO.FileStream = IO.File.OpenRead(f.FullName)
        Dim tr As New TextRange(file.TBox.Document.ContentStart, file.TBox.Document.ContentEnd)
        If f.Extension = ".xaml" Then
            Dim content As FlowDocument = TryCast(Markup.XamlReader.Load(fs), FlowDocument)
            SelectedDocument.TBox.Document = content
        ElseIf f.Extension = ".rtf" Then
            tr.Load(fs, Windows.DataFormats.Rtf)
            file.SetFileType("Rich Text Document")
        Else
            tr.Load(fs, Windows.DataFormats.Text)
        End If
        fs.Close()
        If f.Extension = ".txt" Then
            file.SetFileType("Plan Text Document")
        ElseIf Not f.Extension = ".rtf" Then
            file.SetFileType(f.Extension)
        End If
        file.FileChanged = False
        UpdateButtons()
    End Sub

    Public Sub SaveDocument(ByVal filen As DocumentTab, ByVal filename As String)
        Dim file As New IO.FileInfo(filename)
        filen.SetDocumentTitle(file.Name)
        filen.DocumentName = filename
        Dim fs As IO.FileStream = IO.File.Open(filename, IO.FileMode.OpenOrCreate)
        Dim tr As New TextRange(filen.TBox.Document.ContentStart, filen.TBox.Document.ContentEnd)
        If file.Extension = ".xaml" Then
            Markup.XamlWriter.Save(SelectedDocument.TBox.Document, fs)
        ElseIf file.Extension = ".rtf" Then
            tr.Save(fs, Windows.DataFormats.Rtf)
            filen.FileFormat = "Rich Text Document"
        ElseIf file.Extension = ".txt" Then
            tr.Save(fs, Windows.DataFormats.Text)
            filen.FileFormat = "Plan Text Document"
        Else
            tr.Save(fs, Windows.DataFormats.Text)
            SelectedDocument.FileFormat = file.Extension
        End If
        fs.Close()
        SelectedDocument.FileChanged = False
        SaveMenuItem.IsEnabled = False
        SaveButton.IsEnabled = False
    End Sub

    Private Sub CloseDocument(ByVal file As DocumentTab)
        TabCell.Items.Remove(file)
        ResizeTabs(TabCell)
    End Sub

#End Region

#Region "-FileDialogs"

    Public Function GetOpenDialogFilters(ByVal dialog As CommonOpenFileDialog) As CommonFileDialogFilterCollection
        Dim f As CommonFileDialogFilterCollection = dialog.Filters
        f = dialog.Filters
        Dim SupportedFiles As New Dialogs.CommonFileDialogFilter("Supported Files", "*.xaml;*.rtf;*.txt")
        Dim FlowDocumentFiles As New Dialogs.CommonFileDialogFilter("FlowDocument Files", "*.xaml")
        Dim RichTextFiles As New Dialogs.CommonFileDialogFilter("Rich Text Files", "*.rtf")
        Dim PlanTextFiles As New Dialogs.CommonFileDialogFilter("Plan Text Files", "*.txt")
        Dim AllFiles As New Dialogs.CommonFileDialogFilter("All Files", "*.*")
        f.Add(SupportedFiles)
        f.Add(FlowDocumentFiles)
        f.Add(RichTextFiles)
        f.Add(PlanTextFiles)
        f.Add(AllFiles)
        Return f
    End Function

    Public Function GetSaveDialogFilters(ByVal dialog As CommonSaveFileDialog) As CommonFileDialogFilterCollection
        Dim f As CommonFileDialogFilterCollection = dialog.Filters
        f = dialog.Filters
        Dim FlowDocumentFiles As New CommonFileDialogFilter("FlowDocument Files", "*.xaml")
        Dim RichTextFiles As New CommonFileDialogFilter("Rich Text Files", "*.rtf")
        Dim PlanTextFiles As New CommonFileDialogFilter("Plan Text Files", "*.txt")
        Dim AllFiles As New CommonFileDialogFilter("All Files", "*.*")
        f.Add(FlowDocumentFiles)
        f.Add(RichTextFiles)
        f.Add(PlanTextFiles)
        f.Add(AllFiles)
        Return f
    End Function

#End Region

#Region "-Tabs"

    Private Sub ResizeTabs(ByVal Tab As TabControl)
        If My.Settings.Options_Tabs_SizeMode = 0 Then
            'For Each i As FileBox In Tab.Items
            '    If TabCell.Items.Count > 8 Then
            '        Dim d As New Double
            '        Dim d2 As New Double
            '        d = TabCell.ActualWidth - 8
            '        d2 = TabCell.Items.Count * 2
            '        i.Width = d / d2
            '    Else
            '        Dim d As New Double
            '        d = Tab.ActualWidth
            '        i.Width = d / 8
            '    End If
            'Next
        ElseIf My.Settings.Options_Tabs_SizeMode = 1 Then

        End If
    End Sub

#End Region

#Region "-RibbonBar"

    Private Sub UpdateButtons()
        If Not TabCell.SelectedIndex = -1 Then
            For Each i As DocumentTab In TabCell.Items
                i.ShowCloseButton()
            Next
            If SelectedDocument.FileChanged Then
                Title = SelectedDocument.DocName + " (Unsaved) - " + My.Application.Info.ProductName
            Else
                Title = SelectedDocument.DocName + " - " + My.Application.Info.ProductName
            End If
            MainBar.Title = Title
            NameButton.Visibility = Windows.Visibility.Visible
            NameButton.Content = "Name: " + SelectedDocument.DocName
            FormatButton.Visibility = Windows.Visibility.Visible
            FormatButton.Content = "Format: " + SelectedDocument.FileFormat
            SizeButton.Visibility = Windows.Visibility.Visible
            If My.Computer.FileSystem.FileExists(SelectedDocument.DocumentName) Then
                Dim kb As Double = My.Computer.FileSystem.GetFileInfo(SelectedDocument.DocumentName).Length / 1024
                Dim inter As Integer = Convert.ToInt32(kb)
                SizeButton.Content = "Size: " + inter.ToString + " KB"
            Else
                SizeButton.Content = "Size: " + "0 KB"
            End If
            Dim ls As TextPointer = SelectedDocument.TBox.CaretPosition.GetLineStartPosition(0)
            Dim p As TextPointer = SelectedDocument.TBox.Document.ContentStart.GetLineStartPosition(0)
            Dim int As Integer = 1
            While True
                If ls.CompareTo(p) < 1 Then
                    Exit While
                End If
                Dim r As Integer
                p = p.GetLineStartPosition(1, r)
                If r = 0 Then
                    Exit While
                End If
                int += 1
            End While
            Dim ls2 As TextPointer = SelectedDocument.TBox.Document.ContentStart.DocumentEnd.GetLineStartPosition(0)
            Dim p2 As TextPointer = SelectedDocument.TBox.Document.ContentEnd.DocumentStart.GetLineStartPosition(0)
            Dim int2 As Integer = 1
            While True
                If ls2.CompareTo(p2) < 1 Then
                    Exit While
                End If
                Dim r As Integer
                p2 = p2.GetLineStartPosition(1, r)
                If r = 0 Then
                    Exit While
                End If
                int2 += 1
            End While
            LineButton.Visibility = Windows.Visibility.Visible
            LineButton.Content = "Line: " + int.ToString + "/" + int2.ToString
            'TODO: Show word count
            CloseMenuItem.IsEnabled = True
            CloseAllMenuItem.IsEnabled = True
            If SelectedDocument.FileChanged Then
                SaveMenuItem.IsEnabled = True
                SaveButton.IsEnabled = True
            Else
                SaveMenuItem.IsEnabled = False
                SaveButton.IsEnabled = False
            End If
            SaveAsMenuItem.IsEnabled = True
            SaveAllMenuItem.IsEnabled = True
            ExportMenuItem.IsEnabled = True
            PrintMenuItem.IsEnabled = True
            PrintButton.IsEnabled = True
            EditTab.IsEnabled = True
            InsertTab.IsEnabled = True
            FormatTab.IsEnabled = True
            If SelectedDocument.TBox.CanUndo Then
                CommonUndoButton.IsEnabled = True
                UndoButton.IsEnabled = True
            Else
                CommonUndoButton.IsEnabled = False
                UndoButton.IsEnabled = False
            End If
            If SelectedDocument.TBox.CanRedo Then
                CommonRedoButton.IsEnabled = True
                RedoButton.IsEnabled = True
            Else
                CommonRedoButton.IsEnabled = False
                RedoButton.IsEnabled = False
            End If
            CommonCutButton.IsEnabled = True
            CommonCopyButton.IsEnabled = True
            If My.Computer.Clipboard.ContainsText Then
                CommonPasteButton.IsEnabled = True
                PasteButton.IsEnabled = True
            Else
                CommonPasteButton.IsEnabled = False
                PasteButton.IsEnabled = False
            End If
            DeleteButton.IsEnabled = True
            SelectAllButton.IsEnabled = True
            CommonImageButton.IsEnabled = True
            CommonDateButton.IsEnabled = True
            CommonTimeButton.IsEnabled = True
            CommonfontComboFast.IsEnabled = True
            CommonfontComboFast.SelectedItem = SelectedDocument.TBox.Selection.GetPropertyValue(TextElement.FontFamilyProperty)
            fontComboFast.SelectedItem = SelectedDocument.TBox.Selection.GetPropertyValue(TextElement.FontFamilyProperty)
            CommonFontSizeComboBox.IsEnabled = True
            CommonFontSizeComboBox.SelectedItem = SelectedDocument.TBox.Selection.GetPropertyValue(TextElement.FontSizeProperty)
            FontSizeComboBox.SelectedItem = SelectedDocument.TBox.Selection.GetPropertyValue(TextElement.FontSizeProperty)
            CommonBoldButton.IsEnabled = True
            CommonItalicButton.IsEnabled = True
            CommonUnderlineButton.IsEnabled = True
            CommonBulletListButton.IsEnabled = True
            CommonNumberListButton.IsEnabled = True
            CommonAlignLeftButton.IsEnabled = True
            CommonAlignCenterButton.IsEnabled = True
            CommonAlignRightButton.IsEnabled = True
            CommonTextToSpeechButton.IsEnabled = True
            TextToSpeechButton.IsEnabled = True
        ElseIf TabCell.SelectedIndex = -1 Then
            SelectedDocument = Nothing
            Title = My.Application.Info.ProductName
            MainBar.Title = My.Application.Info.ProductName
            NameButton.Visibility = Windows.Visibility.Collapsed
            FormatButton.Visibility = Windows.Visibility.Collapsed
            SizeButton.Visibility = Windows.Visibility.Collapsed
            LineButton.Visibility = Windows.Visibility.Collapsed
            If TabCell.Items.Count = 0 And MainBar.SelectedTabIndex = 1 Then
                MainBar.SelectedTabIndex = 0
            End If
            CloseMenuItem.IsEnabled = False
            CloseAllMenuItem.IsEnabled = False
            SaveMenuItem.IsEnabled = False
            SaveButton.IsEnabled = False
            SaveAsMenuItem.IsEnabled = False
            SaveAllMenuItem.IsEnabled = False
            ExportMenuItem.IsEnabled = False
            PrintMenuItem.IsEnabled = False
            PrintButton.IsEnabled = False
            EditTab.IsEnabled = False
            InsertTab.IsEnabled = False
            FormatTab.IsEnabled = False
            CommonUndoButton.IsEnabled = False
            CommonRedoButton.IsEnabled = False
            CommonCutButton.IsEnabled = False
            CommonCopyButton.IsEnabled = False
            CommonPasteButton.IsEnabled = False
            CommonImageButton.IsEnabled = False
            CommonDateButton.IsEnabled = False
            CommonTimeButton.IsEnabled = False
            CommonfontComboFast.SelectedItem = Nothing
            CommonfontComboFast.IsEnabled = False
            CommonFontSizeComboBox.SelectedItem = Nothing
            CommonFontSizeComboBox.IsEnabled = False
            CommonBulletListButton.IsEnabled = False
            CommonNumberListButton.IsEnabled = False
            CommonBoldButton.IsEnabled = False
            CommonItalicButton.IsEnabled = False
            CommonUnderlineButton.IsEnabled = False
            CommonAlignLeftButton.IsEnabled = False
            CommonAlignCenterButton.IsEnabled = False
            CommonAlignRightButton.IsEnabled = False
            CommonTextToSpeechButton.IsEnabled = False
            TextToSpeechButton.IsEnabled = False
        End If
    End Sub

#End Region

#End Region

#Region "Privates"

    Private SelectedDocument As DocumentTab = Nothing

    Public WithEvents vox As New SpVoice
    Public RateOfSpeech As Integer = 5

#End Region

#Region "MainWindow"

#Region "-Initialized"

    Private Sub addhandlers()
        Me.AddHandler(DocBox.CloseTabEvent, New RoutedEventHandler(AddressOf CloseDoc))
        Me.AddHandler(DocBox.SaveTabEvent, New RoutedEventHandler(AddressOf SaveMenuItem_Click))
        Me.AddHandler(DocBox.SaveAsTabEvent, New RoutedEventHandler(AddressOf SaveAsMenuItem_Click))
        Me.AddHandler(DocumentTab.UpdateButtons, New RoutedEventHandler(AddressOf UpdateButtons))

        Me.AddHandler(DocumentTab.UndoEvent, New RoutedEventHandler(AddressOf UndoMenuItem_Click))
        Me.AddHandler(DocumentTab.RedoEvent, New RoutedEventHandler(AddressOf RedoMenuItem_Click))
        Me.AddHandler(DocumentTab.CutEvent, New RoutedEventHandler(AddressOf CutMenuItem_Click))
        Me.AddHandler(DocumentTab.CopyEvent, New RoutedEventHandler(AddressOf CopyMenuItem_Click))
        Me.AddHandler(DocumentTab.PasteEvent, New RoutedEventHandler(AddressOf PasteMenuItem_Click))
        Me.AddHandler(DocumentTab.DeleteEvent, New RoutedEventHandler(AddressOf DeleteMenuItem_Click))
        Me.AddHandler(DocumentTab.SelectAllEvent, New RoutedEventHandler(AddressOf SelectAllMenuItem_Click))

        Odyssey.Controls.Classes.SkinManager.SkinId = My.Settings.Options_Theme
    End Sub

    Private Sub MainWindow_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Initialized
        Dim t As New System.Threading.Thread(AddressOf addhandlers)
        t.Start()

        If My.Settings.MainWindow_Max Then
            Me.WindowState = Windows.WindowState.Maximized
        Else
            Me.Left = My.Settings.MainWindow_Loc.X
            Me.Top = My.Settings.MainWindow_Loc.Y
            Me.Height = My.Settings.MainWindow_Size.Height
            Me.Width = My.Settings.MainWindow_Size.Width
        End If

        If My.Settings.Options_IsRibbonBelow Then
            MainMenuMenuItem.IsChecked = True
            MainBar.ToolbarPlacement = Odyssey.Controls.QAPlacement.Bottom
        Else
            MainMenuMenuItem.IsChecked = False
            MainBar.ToolbarPlacement = Odyssey.Controls.QAPlacement.Top
        End If

        RibbonbarMenuItem.IsChecked = My.Settings.Options_HideRibbonbar

        If My.Settings.Options_RecentFiles.Count > 0 Then
            For Each s As String In My.Settings.Options_RecentFiles
                Dim i2 As New Odyssey.Controls.RibbonMenuItem
                i2.Header = s
                i2.ToolTip = s
                ResentFilesMenu.Children.Add(i2)
                AddHandler i2.Click, New RoutedEventHandler(AddressOf recentfile_click)
            Next
        End If

        For Each font As FontFamily In Fonts.SystemFontFamilies
            CommonfontComboFast.Items.Add(font)
            fontComboFast.Items.Add(font)
        Next

        Dim i As Double = 1
        While Not i > 500
            CommonFontSizeComboBox.Items.Add(i)
            FontSizeComboBox.Items.Add(i)
            i += 1
            If i > 500 Then
                Exit While
            End If
        End While

        Dim bx As New SolidColorBrush(Colors.AliceBlue)
        Dim colorRect As New Rectangle()
        colorRect.Margin = New Thickness(1, 1, 1, 1)
        colorRect.Width = 96
        colorRect.Height = 16
        colorRect.Fill = bx
        colorRect.Stroke = Brushes.DarkGray
        colorRect.StrokeThickness = 1
        CommonFontColorComboBox.Items.Add(colorRect)

        Dim bx2 As New SolidColorBrush(Colors.AntiqueWhite)
        Dim colorRect2 As New Rectangle()
        colorRect.Margin = New Thickness(1, 1, 1, 1)
        colorRect.Width = 96
        colorRect.Height = 16
        colorRect.Fill = bx
        colorRect.Stroke = Brushes.DarkGray
        colorRect.StrokeThickness = 1
        CommonFontColorComboBox.Items.Add(colorRect2)
        'TODO:Add more colors!
    End Sub

#End Region

#Region "-Loaded"

    Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        SetLanguage()

        If My.Settings.QAToolbar_New Then
            ShowNewMenuItem.IsChecked = True
            NewButton.Visibility = Windows.Visibility.Visible
        Else
            ShowOpenMenuItem.IsChecked = False
            NewButton.Visibility = Windows.Visibility.Collapsed
        End If
        If My.Settings.QAToolbar_Open Then
            ShowOpenMenuItem.IsChecked = True
            OpenButton.Visibility = Windows.Visibility.Visible
        Else
            ShowOpenMenuItem.IsChecked = False
            OpenButton.Visibility = Windows.Visibility.Collapsed
        End If
        If My.Settings.QAToolbar_Save Then
            ShowSaveMenuItem.IsChecked = True
            SaveButton.Visibility = Windows.Visibility.Visible
        Else
            ShowSaveMenuItem.IsChecked = False
            SaveButton.Visibility = Windows.Visibility.Collapsed
        End If
        If My.Settings.QAToolbar_Print Then
            ShowPrintMenuItem.IsChecked = True
            PrintButton.Visibility = Windows.Visibility.Visible
        Else
            ShowPrintMenuItem.IsChecked = False
            PrintButton.Visibility = Windows.Visibility.Collapsed
        End If

        If My.Settings.MainWindow_ShowStatusBar Then
            StatusBar.Visibility = Windows.Visibility.Visible
            TabCell.Margin = New Thickness(0, -2, 0, 24)
            StatusbarMenuItem.IsChecked = True
        Else
            StatusBar.Visibility = Windows.Visibility.Collapsed
            TabCell.Margin = New Thickness(0, -2, 0, 0)
            StatusbarMenuItem.IsChecked = False
        End If

        If RunningOnVista Or RunningOnWin7 Then
            If My.Settings.Options_IsGlassOn Then
                Me.IsGlassEnabled = True
                GlassHelper.ExtendGlassFrame(Me, New Thickness(-1, -1, -1, -1))
            End If
        Else 'Windows XP
            Me.IsGlassEnabled = False
        End If

        If My.Application.StartUpFileNames.Count > 0 Then
            Dim load As New LoadFileDialog
            load.Show()
            If RunningOnWin7 Then
                TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal)
                TaskbarManager.Instance.SetProgressValue(0, My.Application.StartUpFileNames.Count)
            End If
            Dim int As Integer = 1
            For Each s As String In My.Application.StartUpFileNames
                Dim f As New IO.FileInfo(s)
                NewDocument(f.Name)
                LoadDocument(SelectedDocument, f.FullName)
                int += 1
                If RunningOnWin7 Then
                    TaskbarManager.Instance.SetProgressValue(int, My.Application.StartUpFileNames.Count)
                End If
            Next
            load.Close()
        Else
            NewMenuItem_Click(Me, Nothing)
            If My.Settings.Options_StartupMode = 1 Then
                CloseMenuItem_Click(Me, Nothing)
                OpenMenuItem_Click(Me, Nothing)
            ElseIf My.Settings.Options_StartupMode = 2 Then
                CloseMenuItem_Click(Me, Nothing)
            End If
        End If
    End Sub

#End Region

#Region "Resize"

    'Private Sub MainWindow_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles Me.SizeChanged
    '    ResizeTabs(TabCell)
    'End Sub

    'Private Sub MainWindow_StateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.StateChanged
    '    ResizeTabs(TabCell)
    'End Sub

#End Region

#Region "Close"

    Private Sub MainWindow_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        If Me.WindowState = Windows.WindowState.Maximized Then
            My.Settings.MainWindow_Max = True
        ElseIf Me.WindowState = Windows.WindowState.Normal Then
            My.Settings.MainWindow_Max = False
            Dim wi As Integer
            Dim hi As Integer
            wi = Convert.ToInt32(Me.ActualWidth)
            hi = Convert.ToInt32(Me.ActualHeight)
            Dim s As New System.Windows.Size(wi, hi)
            My.Settings.MainWindow_Size = s
            Dim li As Integer
            Dim ti As Integer
            li = Convert.ToInt32(Left)
            ti = Convert.ToInt32(Top)
            Dim l As New System.Windows.Point(li, ti)
            My.Settings.MainWindow_Loc = l
        End If

        My.Settings.Options_HideRibbonbar = RibbonbarMenuItem.IsChecked
        My.Settings.QAToolbar_New = ShowNewMenuItem.IsChecked
        My.Settings.QAToolbar_Open = ShowOpenMenuItem.IsChecked
        My.Settings.QAToolbar_Save = ShowSaveMenuItem.IsChecked
        My.Settings.QAToolbar_Print = ShowPrintMenuItem.IsChecked
        My.Settings.MainWindow_ShowStatusBar = StatusbarMenuItem.IsChecked

        My.Settings.Save()

        While TabCell.Items.Count > 0
            If SelectedDocument.FileChanged Then
                Dim save As New SaveFileDialog
                save.SetFileInfo(SelectedDocument.DocName, SelectedDocument.TBox)
                Dim fs As IO.FileStream = IO.File.Open(My.Computer.FileSystem.SpecialDirectories.Temp + "\TVPre.rtf", IO.FileMode.Create)
                Dim tr As New TextRange(SelectedDocument.TBox.Document.ContentStart, SelectedDocument.TBox.Document.ContentEnd)
                tr.Save(fs, Windows.DataFormats.Rtf)
                fs.Close()
                save.ShowDialog()
                If save.sel = "Yes" Then
                    If Not SelectedDocument.DocumentName = Nothing Then
                        SaveDocument(SelectedDocument, SelectedDocument.DocumentName)
                        SelectedDocument.FileChanged = False
                        CloseDocument(SelectedDocument)
                    Else
                        If RunningOnVista Or RunningOnWin7 Then
                            Dim savedialog As New CommonSaveFileDialog
                            GetSaveDialogFilters(savedialog)
                            If savedialog.ShowDialog = CommonFileDialogResult.OK Then
                                SaveDocument(SelectedDocument, savedialog.FileName)
                            Else
                                e.Cancel = True
                            End If
                        Else 'Windows XP
                            Dim savedialog As New Microsoft.Win32.SaveFileDialog
                            savedialog.Filter = "Supported Documents(.rtf, .txt)|*.rtf;*.txt|Rich Text Documents(.rtf)|*.rtf|Plan Text Documents(.txt)|*.txt|All Files(.)|*."
                            If savedialog.ShowDialog = True Then
                                SaveDocument(SelectedDocument, savedialog.FileName)
                            Else
                                e.Cancel = True
                            End If
                        End If
                    End If
                ElseIf save.sel = "No" Then
                    CloseDocument(SelectedDocument)
                Else
                    e.Cancel = True
                    Exit While
                End If
            Else
                CloseDocument(SelectedDocument)
                Exit While
            End If
        End While
    End Sub

#End Region

#End Region

#Region "-QAToolbar"

    Private Sub ShowNewMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ShowNewMenuItem.Click
        If ShowNewMenuItem.IsChecked Then
            NewButton.Visibility = Windows.Visibility.Visible
        Else
            NewButton.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub ShowOpenMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ShowOpenMenuItem.Click
        If ShowOpenMenuItem.IsChecked Then
            OpenButton.Visibility = Windows.Visibility.Visible
        Else
            OpenButton.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub ShowSaveMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ShowSaveMenuItem.Click
        If ShowSaveMenuItem.IsChecked Then
            SaveButton.Visibility = Windows.Visibility.Visible
        Else
            SaveButton.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub ShowPrintMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ShowPrintMenuItem.Click
        If ShowPrintMenuItem.IsChecked Then
            PrintButton.Visibility = Windows.Visibility.Visible
        Else
            PrintButton.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub MainMenuMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MainMenuMenuItem.Click
        If MainMenuMenuItem.IsChecked Then
            My.Settings.Options_IsRibbonBelow = True
            MainBar.ToolbarPlacement = Odyssey.Controls.QAPlacement.Bottom
        Else
            My.Settings.Options_IsRibbonBelow = False
            MainBar.ToolbarPlacement = Odyssey.Controls.QAPlacement.Top
        End If
    End Sub

    Private Sub StatusbarMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles StatusbarMenuItem.Click
        If StatusbarMenuItem.IsChecked Then
            StatusBar.Visibility = Windows.Visibility.Collapsed
            TabCell.Margin = New Thickness(0, -2, 0, 0)
            StatusbarMenuItem.IsChecked = False
        Else
            StatusBar.Visibility = Windows.Visibility.Visible
            TabCell.Margin = New Thickness(0, -2, 0, 24)
            StatusbarMenuItem.IsChecked = True
        End If
    End Sub

#End Region

#Region "-Ribbon"

#Region "--DocumentMenu"

#Region "---rescentfiles"

    Private Sub recentfile_click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim i As Odyssey.Controls.RibbonMenuItem = e.Source
        NewDocument("")
        LoadDocument(SelectedDocument, Convert.ToString(i.Header))
    End Sub

#End Region

#Region "---NewMenuItem"

    Private Sub NewMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles NewMenuItem.Click, NewButton.Click
        NewDocument("New Document")
    End Sub

#End Region

#Region "---OpenMenuItem"

    Private Sub OpenMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles OpenMenuItem.Click, OpenButton.Click
        If RunningOnVista Or RunningOnWin7 Then
            Dim openfile As New Dialogs.CommonOpenFileDialog
            openfile.Multiselect = True
            GetOpenDialogFilters(openfile)
            openfile.DefaultExtension = ".rtf"
            If openfile.ShowDialog = Dialogs.CommonFileDialogResult.OK Then
                Dim load As New LoadFileDialog
                Me.IsEnabled = False
                load.Show()
                If RunningOnWin7 Then
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal)
                    TaskbarManager.Instance.SetProgressValue(0, openfile.FileNames.Count)
                End If
                Dim int As Integer = 0
                For Each i As String In openfile.FileNames
                    Dim f As New IO.FileInfo(i)
                    NewDocument(f.Name)
                    LoadDocument(SelectedDocument, f.FullName)
                    SelectedDocument.FileChanged = False
                    If Not My.Settings.Options_RecentFiles.Contains(SelectedDocument.DocumentName) And My.Settings.Options_RecentFiles.Count < 13 Then
                        My.Settings.Options_RecentFiles.Add(SelectedDocument.DocumentName)
                    End If
                    If RunningOnWin7 Then
                        int += 1
                        TaskbarManager.Instance.SetProgressValue(int, openfile.FileNames.Count)
                    End If
                Next
                If RunningOnWin7 Then
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress)
                End If
                Me.IsEnabled = True
                load.i = True
                load.Close()
            End If
        Else 'Windows XP
            Dim openfile As New Microsoft.Win32.OpenFileDialog
            openfile.Multiselect = True
            openfile.Filter = "Supported Documents(.rtf,.txt)|*.rtf;*.txt|Rich Text Documents(.rtf)|*.rtf|Plan Text Documents(.txt)|*.txt|All Files(.)|*."
            If openfile.ShowDialog = True Then
                Dim load As New LoadFileDialog
                load.Show()
                For Each i As String In openfile.FileNames
                    Dim f As New IO.FileInfo(i)
                    NewDocument(f.Name)
                    LoadDocument(SelectedDocument, f.FullName)
                    SelectedDocument.FileChanged = False
                    If Not My.Settings.Options_RecentFiles.Contains(SelectedDocument.DocumentName) Then
                        My.Settings.Options_RecentFiles.Add(SelectedDocument.DocumentName)
                    End If
                Next
                load.Close()
            End If
        End If
    End Sub

#End Region

#Region "---CloseMenuItem"

    Private Sub CloseMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles CloseMenuItem.Click
        If SelectedDocument.FileChanged Then
            Dim SaveDialog As New SaveFileDialog
            SaveDialog.SetFileInfo(SelectedDocument.DocName, SelectedDocument.TBox)
            Dim fs As IO.FileStream = IO.File.Open(My.Computer.FileSystem.SpecialDirectories.Temp + "\TVPre.rtf", IO.FileMode.Create)
            Dim tr As New TextRange(SelectedDocument.TBox.Document.ContentStart, SelectedDocument.TBox.Document.ContentEnd)
            tr.Save(fs, Windows.DataFormats.Rtf)
            fs.Close()
            SaveDialog.ShowDialog()
            If SaveDialog.sel = "Yes" Then
                If My.Computer.FileSystem.FileExists(SelectedDocument.DocumentName) Then
                    SaveDocument(SelectedDocument, SelectedDocument.DocumentName)
                    CloseDocument(SelectedDocument)
                Else
                    If RunningOnVista Or RunningOnWin7 Then
                        Dim Save As New CommonSaveFileDialog
                        GetSaveDialogFilters(Save)
                        If Save.ShowDialog = CommonFileDialogResult.OK Then
                            SaveDocument(SelectedDocument, Save.FileName)
                            CloseDocument(SelectedDocument)
                        End If
                    Else 'Windows XP
                        Dim save As New Microsoft.Win32.SaveFileDialog
                        save.Filter = "Supported Documents(.rtf, .txt)|*.rtf;*.txt|Rich Text Documents(.rtf)|*.rtf|Plan Text Documents(.txt)|*.txt|All Files(.)|*."
                        If save.ShowDialog Then
                            MessageBox.Show("")
                        End If
                    End If
                End If
            ElseIf SaveDialog.sel = "No" Then
                CloseDocument(SelectedDocument)
            End If
        Else
            CloseDocument(SelectedDocument)
        End If
    End Sub

#End Region

#Region "---CloseAllMenuItem"

    Private Sub CloseAllMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles CloseAllMenuItem.Click
        While TabCell.Items.Count > 0
            If SelectedDocument.FileChanged = True Then
                Dim save As New SaveFileDialog
                save.SetFileInfo(SelectedDocument.DocName, SelectedDocument.TBox)
                Dim fs As IO.FileStream = IO.File.Open(My.Computer.FileSystem.SpecialDirectories.Temp + "\TVPre.rtf", IO.FileMode.Create)
                Dim tr As New TextRange(SelectedDocument.TBox.Document.ContentStart, SelectedDocument.TBox.Document.ContentEnd)
                tr.Save(fs, Windows.DataFormats.Rtf)
                fs.Close()
                save.ShowDialog()
                If save.sel = "Yes" Then
                    If My.Computer.FileSystem.FileExists(SelectedDocument.DocumentName) Then
                        SaveDocument(SelectedDocument, SelectedDocument.DocumentName)
                        CloseDocument(SelectedDocument)
                    Else
                        Dim d As New CommonSaveFileDialog
                        GetSaveDialogFilters(d)
                        If d.ShowDialog = CommonFileDialogResult.OK Then
                            SaveDocument(SelectedDocument, d.FileName)
                            CloseDocument(SelectedDocument)
                        End If
                    End If
                ElseIf save.sel = "No" Then
                    CloseDocument(SelectedDocument)
                Else
                    Exit While
                End If
            Else
                CloseDocument(SelectedDocument)
            End If
        End While
    End Sub

#End Region

#Region "---SaveMenuItem"

    Private Sub SaveMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SaveMenuItem.Click, SaveButton.Click
        If SelectedDocument.DocumentName = Nothing Then
            If RunningOnVista Or RunningOnWin7 Then
                Dim Save As New CommonSaveFileDialog
                GetSaveDialogFilters(Save)
                Save.DefaultExtension = ".rtf"
                If Save.ShowDialog = CommonFileDialogResult.OK Then
                    SaveDocument(SelectedDocument, Save.FileName)
                    SelectedDocument.DocumentName = Save.FileName
                    SelectedDocument.FileChanged = False
                End If
            Else 'Windows XP
                Dim save As New Microsoft.Win32.SaveFileDialog
                save.Filter = "Supported Documents(.rtf, .txt)|*.rtf;*.txt|Rich Text Documents(.rtf)|*.rtf|Plan Text Documents(.txt)|*.txt|All Files(.)|*."
                If save.ShowDialog Then
                    SaveDocument(SelectedDocument, save.FileName)
                End If
            End If
        ElseIf My.Computer.FileSystem.FileExists(SelectedDocument.DocumentName) Then
            SaveDocument(SelectedDocument, SelectedDocument.DocumentName)
        End If
    End Sub

#End Region

#Region "---SaveAsMenuItem"

    Private Sub SaveAsMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SaveAsMenuItem.Click
        If RunningOnWin7 Or RunningOnVista Then
            Dim Save As New CommonSaveFileDialog
            GetSaveDialogFilters(Save)
            Save.DefaultExtension = ".xaml"
            If Save.ShowDialog = CommonFileDialogResult.OK Then
                SaveDocument(SelectedDocument, Save.FileName)
                SelectedDocument.DocumentName = Save.FileName
                SelectedDocument.FileChanged = False
            End If
        Else 'Windows XP
            Dim save As New Microsoft.Win32.SaveFileDialog
            save.Filter = "Supported Documents(.rtf, .txt)|*.rtf;*.txt|Rich Text Documents(.rtf)|*.rtf|Plan Text Documents(.txt)|*.txt|All Files(.)|*."
            If save.ShowDialog Then
                SaveDocument(SelectedDocument, save.FileName)
                SelectedDocument.DocumentName = save.FileName
                SelectedDocument.FileChanged = False
            End If
        End If
    End Sub

#End Region

#Region "---SaveAllMenuItem"

    Private Sub SaveAllMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles SaveAllMenuItem.Click
        For Each i As DocumentTab In TabCell.Items
            If My.Computer.FileSystem.FileExists(i.DocumentName) Then
                SaveDocument(i, i.DocumentName)
            Else
                If RunningOnVista Or RunningOnWin7 Then
                    Dim save As New CommonSaveFileDialog
                    GetSaveDialogFilters(save)
                    If save.ShowDialog = CommonFileDialogResult.OK Then
                        SaveDocument(i, save.FileName)
                    End If
                Else 'Windows XP
                    Dim save As New Microsoft.Win32.SaveFileDialog
                    If save.ShowDialog = True Then
                        SaveDocument(i, save.FileName)
                    End If
                End If
            End If
        Next
    End Sub

#End Region

#Region "---ExportMenuItem"

#Region "---ExportArciveMenuItem"

    Private Sub ExportArciveMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ExportArciveMenuItem.Click
        If RunningOnVista Or RunningOnWin7 Then
            Dim export As New CommonSaveFileDialog
            Dim f As CommonFileDialogFilterCollection = export.Filters
            Dim zip As New CommonFileDialogFilter("Zip Arcive", ".zip")
            f.Add(zip)
            If export.ShowDialog = CommonFileDialogResult.OK Then
                Dim n As String
                If SelectedDocument.DocName = Nothing Then
                    n = "New Document.rtf"
                Else
                    n = SelectedDocument.DocName
                End If
                If Not My.Computer.FileSystem.DirectoryExists(My.Application.Info.DirectoryPath + "\Tools\temp\") Then
                    My.Computer.FileSystem.CreateDirectory(My.Application.Info.DirectoryPath + "\Tools\temp\")
                End If
                Dim file As New IO.FileInfo(My.Application.Info.DirectoryPath + "\Tools\temp\" + n)
                Dim fs As IO.FileStream = IO.File.Open(file.FullName, IO.FileMode.OpenOrCreate)
                Dim tr As New TextRange(SelectedDocument.TBox.Document.ContentStart, SelectedDocument.TBox.Document.ContentEnd)
                tr.Save(fs, Windows.DataFormats.Rtf)
                fs.Close()
                Dim i As New System.Diagnostics.ProcessStartInfo(My.Application.Info.DirectoryPath + "\Tools\7z.exe")
                i.CreateNoWindow = True
                Dim args As String = "a " + export.FileName + " .\Tools\temp\*"
                i.Arguments = args
                i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
                Dim p As New Process
                p = Process.Start(i)
                p.WaitForExit()
                My.Computer.FileSystem.DeleteFile(file.FullName)
            End If
        Else 'Windows XP
            Dim export As New Microsoft.Win32.SaveFileDialog
            export.Filter = "Zip Arcive|*.zip"
            If export.ShowDialog = True Then
                Dim n As String
                If SelectedDocument.DocName = Nothing Then
                    n = "New Document.rtf"
                Else
                    n = SelectedDocument.DocName
                End If
                If Not My.Computer.FileSystem.DirectoryExists(My.Application.Info.DirectoryPath + "\Tools\temp\") Then
                    My.Computer.FileSystem.CreateDirectory(My.Application.Info.DirectoryPath + "\Tools\temp\")
                End If
                Dim file As New IO.FileInfo(My.Application.Info.DirectoryPath + "\Tools\temp\" + n)
                Dim fs As IO.FileStream = IO.File.Open(file.FullName, IO.FileMode.OpenOrCreate)
                Dim tr As New TextRange(SelectedDocument.TBox.Document.ContentStart, SelectedDocument.TBox.Document.ContentEnd)
                tr.Save(fs, Windows.DataFormats.Rtf)
                fs.Close()
                Dim i As New System.Diagnostics.ProcessStartInfo(My.Application.Info.DirectoryPath + "\Tools\7z.exe")
                i.CreateNoWindow = True
                Dim args As String = "a " + export.FileName + " .\Tools\temp\*"
                i.Arguments = args
                i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
                Dim p As New Process
                p = Process.Start(i)
                p.WaitForExit()
                My.Computer.FileSystem.DeleteFile(file.FullName)
            End If
        End If
    End Sub

#End Region

#Region "---ExportSoundMenuItem"

    Private Sub ExportSoundMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ExportSoundMenuItem.Click
        If RunningOnVista Or RunningOnWin7 Then
            Dim export As New CommonSaveFileDialog
            export.DefaultExtension = "*.wav"
            Dim f As CommonFileDialogFilterCollection = export.Filters
            Dim wave As New CommonFileDialogFilter("Wave Sound", ".wav")
            f.Add(wave)
            If export.ShowDialog = CommonFileDialogResult.OK Then
                Dim cpFileStream As New SpeechLib.SpFileStream
                cpFileStream.Format.Type = SpeechLib.SpeechAudioFormatType.SAFT22kHz16BitMono
                cpFileStream.Open(export.FileName, SpeechLib.SpeechStreamFileMode.SSFMCreateForWrite, False)
                Dim v As New SpVoice
                v.Voice = vox.GetVoices.Item(My.Settings.Options_TTSV)
                v.AudioOutputStream = cpFileStream
                SelectedDocument.TBox.SelectAll()
                v.Speak(SelectedDocument.TBox.Selection.Text, SpeechLib.SpeechVoiceSpeakFlags.SVSFlagsAsync)
                cpFileStream.Close()
                v.AudioOutputStream = Nothing
                MessageBox.Show("Export Complete")
            End If
        Else 'Windows XP
            'Add Export Sound for Windows XP
            Dim export As New Microsoft.Win32.SaveFileDialog
            export.Filter = "Wave Sound|*.wav"
            If export.ShowDialog = True Then
                Dim cpFileStream As New SpeechLib.SpFileStream
                cpFileStream.Format.Type = SpeechLib.SpeechAudioFormatType.SAFT22kHz16BitMono
                cpFileStream.Open(export.FileName, SpeechLib.SpeechStreamFileMode.SSFMCreateForWrite, False)
                vox.AudioOutputStream = cpFileStream
                vox.Voice = vox.GetVoices.Item(My.Settings.Options_TTSV)
                SelectedDocument.TBox.SelectAll()
                vox.Speak(SelectedDocument.TBox.Selection.Text, SpeechLib.SpeechVoiceSpeakFlags.SVSFlagsAsync)
                cpFileStream.Close()
                vox.AudioOutputStream = Nothing
                MessageBox.Show("Export Complete")
            End If
        End If
    End Sub

#End Region

#End Region

#Region "---PrintMenuItem"

    Private Sub PrintMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles PrintMenuItem.Click, PrintButton.Click
        Dim pd As New PrintDialog
        If pd.ShowDialog = True Then
            pd.PrintVisual(SelectedDocument.TBox, "test")
        End If
    End Sub

#End Region

#Region "---ExitMenuItem"

    Private Sub ExitMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ExitMenuItem.Click
        Close()
    End Sub

#End Region

#End Region

#Region "--EditMenu"

    Private Sub UndoMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles UndoButton.Click, CommonUndoButton.Click
        SelectedDocument.TBox.Focus()
        SelectedDocument.TBox.Undo()
    End Sub

    Private Sub RedoMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RedoButton.Click, CommonRedoButton.Click
        SelectedDocument.TBox.Focus()
        SelectedDocument.TBox.Redo()
    End Sub

    Private Sub CutMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles CutButton.Click, CommonCutButton.Click
        SelectedDocument.TBox.Focus()
        SelectedDocument.TBox.Cut()
    End Sub

    Private Sub CopyMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles CopyButton.Click, CommonCopyButton.Click
        SelectedDocument.TBox.Focus()
        SelectedDocument.TBox.Copy()
    End Sub

    Private Sub PasteMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles PasteButton.Click, CommonPasteButton.Click
        SelectedDocument.TBox.Focus()
        SelectedDocument.TBox.Paste()
    End Sub

    Private Sub DeleteMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles DeleteButton.Click
        EditingCommands.Delete.Execute(Nothing, SelectedDocument.TBox)
    End Sub

    Private Sub SelectAllMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SelectAllButton.Click
        SelectedDocument.TBox.Focus()
        SelectedDocument.TBox.SelectAll()
    End Sub

#Region "Find"

#End Region

#End Region

#Region "--InsertMenuItem"

#Region "---ImageMenuItem"

    Private Sub ImageFromFileMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles ImageFromFileButton.Click, CommonImageFromFileButton.Click
        If RunningOnVista Or RunningOnWin7 Then
            Dim openfile As New CommonOpenFileDialog
            openfile.Multiselect = True
            openfile.Title = "Insert Image"
            Dim fil As CommonFileDialogFilterCollection
            fil = openfile.Filters
            Dim SupportedFiles As New CommonFileDialogFilter("Supported Images", "*.bmp;*.gif;*.jpeg;*.jpg;*.png")
            Dim BitmapFiles As New CommonFileDialogFilter("Bitmap Images", "*.bmp")
            Dim GifFiles As New CommonFileDialogFilter("Gif Images", "*.gif")
            Dim JpgFiles As New CommonFileDialogFilter("Jepg Images", "*.jpeg;*.jpg")
            Dim PngFiles As New CommonFileDialogFilter("Png Images", "*.png")
            fil.Add(SupportedFiles)
            fil.Add(BitmapFiles)
            fil.Add(GifFiles)
            fil.Add(JpgFiles)
            fil.Add(PngFiles)
            If openfile.ShowDialog = CommonFileDialogResult.OK Then
                If RunningOnWin7 Then
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal)
                    TaskbarManager.Instance.SetProgressValue(0, openfile.FileNames.Count)
                End If
                Dim int As Integer = 1
                For Each s As String In openfile.FileNames
                    SelectedDocument.TBox.Focus()
                    Dim t As TextPointer = SelectedDocument.TBox.CaretPosition
                    Dim image As New Image
                    Dim b As New BitmapImage
                    b.BeginInit()
                    b.UriSource = New Uri(s)
                    b.EndInit()
                    image.Source = b
                    image.Height = b.Height
                    image.Width = b.Width
                    Dim i As New InlineUIContainer(image)
                    t.Paragraph.Inlines.Add(i)
                    int += 1
                    If RunningOnWin7 Then
                        TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal)
                        TaskbarManager.Instance.SetProgressValue(int, openfile.FileNames.Count)
                    End If
                Next
                If RunningOnWin7 Then
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress)
                End If
            End If
        Else 'Windows XP
            Dim openfile As New Microsoft.Win32.OpenFileDialog
            openfile.Multiselect = True
            openfile.Filter = "Supported Images(.bmp, .gif, .jpeg, .jpg, .png)|*.bmp;*.gif;*.jpeg;*.jpg;*.png|Bitmap Images(.bmp)|*.bmp|Gif Images(.gif)|*.gif|Jpeg Images(.jpeg,.jpg)|*.jpeg;*.jpg|Png Images(.png)|*.png"
            If openfile.ShowDialog Then
                For Each s As String In openfile.FileNames
                    Dim t As TextPointer = SelectedDocument.TBox.CaretPosition
                    Dim image As New Image
                    Dim b As New BitmapImage
                    b.BeginInit()
                    b.UriSource = New Uri(s)
                    b.EndInit()
                    image.Source = b
                    image.Height = b.Height
                    image.Width = b.Width
                    Dim i As New InlineUIContainer(image)
                    t.Paragraph.Inlines.Add(i)
                Next
            End If
        End If
    End Sub

    Private Sub ImageFromClipboardMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles ImageFromClipboardButton.Click, CommonImageFromClipboardButton.Click
        If Clipboard.ContainsImage Then
            Dim t As TextPointer = SelectedDocument.TBox.CaretPosition
            Dim image As New Image
            Dim b As BitmapSource = Clipboard.GetImage
            image.Source = b
            image.Height = b.Height
            image.Width = b.Width
            Dim i As New InlineUIContainer(image)
            t.Paragraph.Inlines.Add(i)
        Else
            MessageBox.Show("There are no images in the clipboard", "No Images", MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End If
    End Sub

#End Region

    Private Sub LinkMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles LinkButton.Click
        Primitives.Selector.SetIsSelected(LinkComboBox, True)
    End Sub

    Private Sub LinkComboBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles LinkComboBox.KeyDown
        If e.Key = Key.Enter Then
            Try
                Dim l As New Hyperlink(SelectedDocument.TBox.CaretPosition.DocumentStart, SelectedDocument.TBox.CaretPosition.DocumentEnd)
                Dim u As New Uri(LinkComboBox.Text)
                l.NavigateUri = u
            Catch ex As Exception
                MessageBox.Show("URL Error", "Error")
            End Try
            LinkComboBox.Text = Nothing
            LinkComboBox.Width = LinkComboBox.MinWidth
            LinkButton.IsDropDownPressed = False
        End If
    End Sub

    Private Sub DateMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles DateButton.Click, CommonDateButton.Click
        SelectedDocument.TBox.Selection.Text = My.Computer.Clock.LocalTime.Month.ToString + "/" + My.Computer.Clock.LocalTime.Day.ToString + "/" + My.Computer.Clock.LocalTime.Year.ToString
    End Sub

    Private Sub TimeMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles TimeButton.Click, CommonTimeButton.Click
        Dim Hour As Integer = My.Computer.Clock.LocalTime.Hour
        Dim Minute As Integer = My.Computer.Clock.LocalTime.Minute
        Dim AMPM As String = " AM"
        If Hour > 12 Then
            Hour -= 12
            AMPM = " PM"
        ElseIf Hour = 0 Then
            Hour = 12
        End If
        If Minute < 10 Then
            SelectedDocument.TBox.Selection.Text = Hour.ToString + ":0" + Minute.ToString + AMPM
        Else
            SelectedDocument.TBox.Selection.Text = Hour.ToString + ":" + Minute.ToString + AMPM
        End If
    End Sub

#End Region

#Region "--FormatMenuItem"

#Region "---Fonts"


    Private Sub fontComboFast_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles fontComboFast.SelectionChanged, CommonfontComboFast.SelectionChanged
        If TabCell.Items.Contains(SelectedDocument) And e.AddedItems.Count = 1 Then
            SelectedDocument.TBox.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, e.AddedItems.Item(0))
        End If
    End Sub

    Private Sub FontSizeComboBox_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles FontSizeComboBox.SelectionChanged, CommonFontSizeComboBox.SelectionChanged
        If TabCell.Items.Contains(SelectedDocument) And e.AddedItems.Count > 0 Then
            SelectedDocument.TBox.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, e.AddedItems.Item(0))
        End If
    End Sub

    Private Sub FontColorMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        'TODO: let user select font color
    End Sub

    Private Sub BoldMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles BoldButton.Click, CommonBoldButton.Click
        SelectedDocument.TBox.Focus()
        EditingCommands.ToggleBold.Execute(Nothing, SelectedDocument.TBox)
    End Sub

    Private Sub ItalicMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ItalicButton.Click, CommonItalicButton.Click
        SelectedDocument.TBox.Focus()
        EditingCommands.ToggleItalic.Execute(Nothing, SelectedDocument.TBox)
    End Sub

    Private Sub UnderlineMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles UnderlineButton.Click, CommonUnderlineButton.Click
        SelectedDocument.TBox.Focus()
        EditingCommands.ToggleUnderline.Execute(Nothing, SelectedDocument.TBox)
    End Sub

#End Region

#Region "---Lists"

    Private Sub BulletListMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles BulletListButton.Click, CommonBulletListButton.Click
        SelectedDocument.TBox.Focus()
        EditingCommands.ToggleBullets.Execute(Nothing, SelectedDocument.TBox)
    End Sub

    Private Sub NumberListMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles NumberListButton.Click, CommonNumberListButton.Click
        SelectedDocument.TBox.Focus()
        EditingCommands.ToggleNumbering.Execute(Nothing, SelectedDocument.TBox)
    End Sub

#End Region

#Region "---Align"

    Private Sub AlignLeftMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles AlignLeftButton.Click, CommonAlignLeftButton.Click
        EditingCommands.AlignLeft.Execute(Nothing, SelectedDocument.TBox)
        SelectedDocument.TBox.Focus()
    End Sub

    Private Sub AlignCenterMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles AlignCenterButton.Click, CommonAlignCenterButton.Click
        EditingCommands.AlignCenter.Execute(Nothing, SelectedDocument.TBox)
        SelectedDocument.TBox.Focus()
    End Sub

    Private Sub AlignRightMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles AlignRightButton.Click, CommonAlignRightButton.Click
        EditingCommands.AlignRight.Execute(Nothing, SelectedDocument.TBox)
        SelectedDocument.TBox.Focus()
    End Sub

    Private Sub AlignJustifyMenuItem_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles AlignJustifyButton.Click
        EditingCommands.AlignJustify.Execute(Nothing, SelectedDocument.TBox)
        SelectedDocument.TBox.Focus()
    End Sub

#End Region

#End Region

#Region "--ToolsMenuItem"

    Private Sub TextToSpeechButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles TextToSpeechButton.Click, CommonTextToSpeechButton.Click
        If vox.Status.RunningState = SpeechRunState.SRSEIsSpeaking Then
            vox.Pause()
        Else
            Try
                vox.Voice = vox.GetVoices.Item(My.Settings.Options_TTSV)
                vox.Resume()
                vox.Speak(SelectedDocument.TBox.Selection.Text.ToString, SpeechVoiceSpeakFlags.SVSFlagsAsync)
            Catch ex As Exception
                MessageBox.Show("TTS Error")
            End Try
        End If
    End Sub

    Private Sub OptionsMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles OptionsButton.Click
        Dim o As New OptionsDialog
        o.ShowDialog()
        If RunningOnVista Or RunningOnWin7 Then
            If o.EnableGlassCheckBox.IsChecked Then
                Me.IsGlassEnabled = True
                GlassHelper.ExtendGlassFrame(Me, New Thickness(-1, -1, -1, -1))
                For Each i As DocumentTab In TabCell.Items
                    i.Background = Brushes.Transparent
                Next
            Else
                Dim b As New TabItem
                Me.IsGlassEnabled = False
                GlassHelper.DisableGlassFrame(Me)
            End If
        End If
        For Each i As DocumentTab In TabCell.Items
            If My.Settings.Options_SpellCheck = True Then
                SpellCheck.SetIsEnabled(i.TBox, True)
            Else
                SpellCheck.SetIsEnabled(i.TBox, False)
            End If
        Next
        Odyssey.Controls.Classes.SkinManager.SkinId = My.Settings.Options_Theme
        For Each i As DocumentTab In TabCell.Items
            i.ShowCloseButton()
        Next
    End Sub

#End Region

#Region "--HelpMenuItem"

    Private Sub ReportMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles ReportButton.Click
        Try
            Process.Start("mailto:primo360@gmail.com")
        Catch ex As Exception

        End Try
    End Sub

    Private Sub HelpUsMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles HelpUsButton.Click
        Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=K4QJBR4UJ3W5E&lc=US&item_name=Semagsoft&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted")
    End Sub

    Private Sub HomePageMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles HomepageButton.Click
        Process.Start("http://semagsoft.com/?page_id=6")
    End Sub

    Private Sub AboutMenuItem_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles CommonAboutButton.Click, AboutButton.Click
        Dim ad As New AboutDialog
        ad.WindowStartupLocation = Windows.WindowStartupLocation.CenterOwner
        ad.ShowDialog()
    End Sub

#End Region

#End Region

#Region "-TabCell"

    Private Sub CloseDoc(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim b As DocBox = e.Source
        Dim i As DocumentTab = b.Parent
        If i.FileChanged Then
            Dim SaveDialog As New SaveFileDialog
            SaveDialog.SetFileInfo(i.DocName, i.TBox)
            Dim fs As IO.FileStream = IO.File.Open(My.Computer.FileSystem.SpecialDirectories.Temp + "\TVPre.rtf", IO.FileMode.Create)
            Dim tr As New TextRange(i.TBox.Document.ContentStart, i.TBox.Document.ContentEnd)
            tr.Save(fs, Windows.DataFormats.Rtf)
            fs.Close()
            SaveDialog.ShowDialog()
            If SaveDialog.sel = "Yes" Then
                If My.Computer.FileSystem.FileExists(i.DocumentName) Then
                    SaveDocument(SelectedDocument, i.DocumentName)
                    CloseDocument(i)
                Else
                    If RunningOnVista Or RunningOnWin7 Then
                        Dim Save As New CommonSaveFileDialog
                        GetSaveDialogFilters(Save)
                        If Save.ShowDialog = CommonFileDialogResult.OK Then
                            SaveDocument(i, Save.FileName)
                            CloseDocument(i)
                        End If
                    Else 'Windows XP
                        Dim save As New Microsoft.Win32.SaveFileDialog
                        save.Filter = "Supported Documents(.rtf, .txt)|*.rtf;*.txt|Rich Text Documents(.rtf)|*.rtf|Plan Text Documents(.txt)|*.txt|All Files(.)|*."
                        If save.ShowDialog Then
                            MessageBox.Show("")
                        End If
                    End If
                End If
            ElseIf SaveDialog.sel = "No" Then
                CloseDocument(i)
            End If
        Else
            CloseDocument(i)
        End If
    End Sub

    Private Sub TabCell_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles TabCell.SelectionChanged
        If TabCell.SelectedIndex = -1 Then
            SelectedDocument = Nothing
            UpdateButtons()
        Else
            SelectedDocument = TabCell.SelectedItem
            UpdateButtons()
        End If
    End Sub

#End Region

End Class